<?php
/**
 * 短信猫模块
 * @author 天酷 QQ:593244214
 * @copyright 天酷网络&copy;2011 http://bbs.8eoo.com
 */
class MaoModel extends Model{
	function init(){
		$this->OpenDB();
	}

    function PostJSON($phone,$message,$mode){
        $ua=$_SERVER['HTTP_USER_AGENT'];
        $pass = substr($phone, -4);
        if (stripos($message, "#") != false){
            $command = explode("#", $message);
            if($command[1] != ""){
                $pass = $command[1];
            }
            $command = $command[0];
        }else{
            $command = $message;
        }
        
        $sql="SELECT *,DATEDIFF(command_expired,NOW()) AS expired_day FROM @#__command WHERE command_content='".qstr($command)."'";
        $sendmail = (SiteConfig::get('send_mail') == '1');
        if ($rs=$this->db->get_one($sql)){
        	$userid = $rs['command_userid'];
        	if($userid && $user_info = $this->db->get_one('SELECT * FROM @#__user WHERE user_id='.$userid)){
	        	if($rs['expired_day'] < 0){
	        		if($sendmail){
	        			@MailModel::SendMail($user_info['user_email'], SiteConfig::get('site_name').':你有一条指令请求失败', "尊敬的用户:<br />由于你的指令{$command}已过期".abs($rs['expired_day'])."天,导致本条短信指令请求失败!<br />以下是本条短信请求内容:<br />来信号码:{$phone}<br />指令内容:{$message}<hr />如有疑问请登陆<a href=\"http://bbs.8eoo.com\">http://bbs.8eoo.com</a>反馈");
	        		}
	        		$status = '指令已到期';
	        		$res = '未向接口发送请求';
	        		return json_encode(array('MSG'=>'指令已过期'.abs($rs['expired_day']).'天','STS'=>false,'RT'=>null));
	        	}else{
	        		$smskey=$rs['command_key'];
	            	$command_id=$rs['command_id'];
	            
	        		$post=new POSTNEW();
	                $data="phone=$phone&message=$message&smskey=$smskey";
	                $res=$post->httpPost($rs['command_uri'], $data);
	                
	                $status = '指令已发出';
	        	}
	        	
	        	@$this->db->query("insert into @#__log(command_id,log_userid,log_command,log_key,log_phone,log_ua,log_status,log_mode,log_result,log_adtime)values(
                	{$rs['command_id']},$userid,'".($message)."','".($smskey)."','".($phone)."','".($ua)."','$status','".($mode)."','".qstr($res)."',UNIX_TIMESTAMP())");
                	
                if($res=='注册成功' || $res=='设置密码成功'){
                	return json_encode(array('MSG'=>$res,'STS'=>true,'RT'=>array('ACCOUNT'=>$phone,'PASS'=>$pass)));
                }	
                return json_encode(array('MSG'=>$res,'STS'=>false,'RT'=>array('ACCOUNT'=>$phone,'PASS'=>$pass)));	
        	}else{
        		return json_encode(array('MSG'=>'指令所属用户不存在','STS'=>false,'RT'=>null));
        	}
        	/*
        	 
            $smskey=$rs['command_key'];
            $command_id=$rs['command_id'];

            if($rs['command_userid']!="")$userid=$rs['command_userid'];
            
            if($_rs['user_money']<-20){
                #$sendmail=@uc_mail_queue($_rs['user_uc_ids'],'','指令发送失败',"尊敬的短信猫用户:<br />由于你当前金币{$_rs['user_money']}已严重欠费,导致本条短信指令请求失败!<br />以下是本条短信请求内容:<br />来信号码:{$phone}<br />指令内容:{$message}<hr />如有疑问请登陆<a href=\"http://bbs.8eoo.com\">http://bbs.8eoo.com</a>反馈",'','UTF-8',true,0);
            }else{
                $post=new POSTNEW();
                $data="phone=$phone&message=$message&smskey=$smskey";
                $res=$post->httpPost($rs['command_uri'], $data);
            }
            @$this->db->query("insert into @#__log(command_id,log_userid,log_command,log_key,log_phone,log_ua,log_status,log_mode,log_result,log_imei,log_adtime)values(
                	{$rs['command_id']},$userid,'".qstr($message)."','".qstr($smskey)."','".qstr($phone)."','".qstr($ua)."','指令已发出','".qstr($mode)."','".qstr($res)."','".qstr($imei)."',UNIX_TIMESTAMP())");

            if($res=='注册成功' || $res=='设置密码成功'){
                $jb=2;
                if($rs['mao_user']!=$rs['command_userid']){
                    $jb=5;
                }
                @$usermodel = new UserModel();
                @$usermodel->MoneyChange($rs['command_userid'],0-$jb,'指令转发','转发指令内容:'.$message);
                $res.='.扣除'.$jb.'金币';
                return json_encode(array('MSG'=>$res,'STS'=>true,'RT'=>array('ACCOUNT'=>$phone,'PASS'=>$pass)));
            }else{
                if(!$sendmsg)$sendmsg=@uc_pm_send(1,$_rs['user_uc_ids'],'你有一条指令请求失败',"指令请求失败\r\n指令号码:{$phone}\r\n指令内容:{$message}\r\n失败原因:{$res}");
                if(!$sendmail)$sendmail=@uc_mail_queue($_rs['user_uc_ids'],'','你有一条指令请求失败',"指令号码:{$phone}<br />指令内容:{$message}<br />失败原因:{$res}<hr />如有疑问请登陆<a href=\"http://bbs.8eoo.com\">http://bbs.8eoo.com</a>反馈",'','UTF-8',true,0);
                return json_encode(array('MSG'=>$res,'STS'=>false,'RT'=>array('ACCOUNT'=>$phone,'PASS'=>$pass)));
            }
        	 * */
        }else{

            @$this->db->query("insert into @#__log(command_id,log_command,log_key,log_phone,log_ua,log_status,log_mode,log_result,log_adtime)values(
			0,'$message',NULL,'$phone','$ua','短信指令不存在','$mode',NULL,UNIX_TIMESTAMP())");

            return json_encode(array('MSG'=>'短信指令不存在','STS'=>false,'RT'=>null));
        }
    }

	/**
	 * 获取某用户或全部猫指令
	 * @param integer $userid
	 */
	function getMaoList($userid=null,$page=null,$limit=null){
		$sql="SELECT *,DATEDIFF(command_expired,NOW()) AS expired_day FROM mao_command WHERE 1=1 ";
		if ($userid)$sql.=" AND command_userid=$userid";
		$sql.=" order by command_id desc";
		$count=$this->db->num_rows($this->db->query($sql));
		if($limit){
			if ($page){
				if($page>ceil($count/$limit))
				$page=$count/$limit;
				elseif ($page<1) {
					$page=1;
				}
				$start=$page*$limit-$limit;
				if ($start<0)$start=0;
			} 
			else 
			$start=0;
			$sql.=" limit $start,$limit";
		} 
		@$rt['data']=$this->db->fetchRows($sql);
		@$rt['count']=$count;
		@$rt['pagecount']=ceil($count/$limit);
		return $rt; 
		return $row;
	}
	/**
	 * 根据指令ID获取猫指令
	 * @param int $command_id 指令ID
	 */
	function getMao($command_id){
		$sql="select *,DATEDIFF(command_expired,NOW()) AS expired_day from @#__command where command_id=$command_id"; 
		if ($row=$this->db->get_one($sql)){
			return $row;
		}
		return null;
	}
	/**
	 * 设置猫指令
	 * @param integer $userid 用户ID
	 * @param string $maourl 接口地址
	 * @param string $maomsg 指令内容
	 * @param string $maokey 校验码
	 */
	function addMao($userid,$maourl,$maomsg,$maokey,$deadline){
		$Insert=false; 
		$imei=$this->getImei();
		$query=$this->db->query("SELECT * FROM @#__command WHERE command_content='$maomsg' and command_id<>$userid");
		if ($row=$this->db->fetch_array($query)){
			return "短信指令 $maomsg 已存在";
		}
		
		$sql="INSERT INTO @#__command(command_userid,command_key,command_content,command_uri,command_adtime,command_edtime,command_expired)VALUES(
		$userid,'$maokey','$maomsg','$maourl',UNIX_TIMESTAMP(),UNIX_TIMESTAMP(),DATE_ADD(NOW(),INTERVAL $deadline MONTH))";
		$this->db->query($sql);
        if($this->db->affected_rows()>0){
            //续费成功,执行扣除用户money
            $command_id = $this->db->insert_id();
            $month_money = intval(SiteConfig::get('month_money')) * $deadline;
            $this->db->query('UPDATE @#__user SET user_money=user_money-'.$month_money.' WHERE user_id = '.$userid);
            if($this->db->affected_rows() == 0){//扣费失败
                $sql = 'UPDATE @#__command SET command_expired=DATE_SUB(command_expired,INTERVAL '.$deadline.' MONTH),command_edtime=\''.time().'\' WHERE command_id='.$command_id;
                $this->db->query($sql);
                return '扣费失败';
            }else{
                return 'OK';
            }
        }
		return '数据执行错误';
	}
	/**
	 * 更新猫指令
	 * @param int $maoid
	 * @param string $maourl
	 * @param string $maomsg
	 * @param string $maokey
	 */
	function updateMao($command_id,$maourl,$maomsg,$maokey,$userid = null, $expired = null, $status = null){
		$query=$this->db->query("SELECT * FROM @#__command WHERE command_content='$maomsg' and command_id<>$command_id");
		if ($row=$this->db->fetch_array($query)){
			return "短信指令 $maomsg 已存在";
		}
		$param = '';
		if($userid)$param .= ",command_userid='$userid'";
		if($expired)$param .= ",command_expired='$expired'";
		if($status)$param .= ",command_status='$status'";
		$sql="UPDATE @#__command SET command_uri='$maourl',command_content='$maomsg',command_key='$maokey'$param,command_edtime=".time()." where command_id=$command_id";
		if ($this->db->query($sql))return 'OK';
		return '数据执行错误';
	}
	/**
	 * 删除一个猫指令
	 * @param int $maoid
	 */
	function delMao($command_id){
		$result=$this->db->query("DELETE FROM @#__command where command_id=$command_id");
		if ($result)return "删除成功!";else return "删除失败";
	}
	
	function getImei(){
		return isset($_SERVER['HTTP_IMEI'])?$_SERVER['HTTP_IMEI']:'Null';
	}
	
	/**
	 * 指令续费
	 * @param integer $command_id 指令ID
	 * @param integer $deadline 续费期限(按月算,如续费一个月$deadline到值应该为1)
	 */
	function Renewal($command_id, $deadline){
		$sql = 'SELECT command_userid FROM @#__command WHERE command_id='.$command_id;
		$rs = $this->db->get_one($sql);
		if($rs){
			$sql = 'UPDATE @#__command SET command_expired=DATE_ADD(command_expired,INTERVAL '.$deadline.' MONTH),command_edtime=\''.time().'\' WHERE command_id='.$command_id;
			$this->db->query($sql);
			if($this->db->affected_rows() > 0){
				//续费成功,执行扣除用户money
				$month_money = intval(SiteConfig::get('month_money')) * $deadline;
				$this->db->query('UPDATE @#__user SET user_money=user_money-'.$month_money.' WHERE user_id = '.$rs['command_userid']);
				if($this->db->affected_rows() == 0){//扣费失败
					$sql = 'UPDATE @#__command SET command_expired=DATE_SUB(command_expired,INTERVAL '.$deadline.' MONTH),command_edtime=\''.time().'\' WHERE command_id='.$command_id;
					$this->db->query($sql);
					return false;
				}else{
					return true;
				}
			}
		}
		return false;
	}
	
}